package org.devio.`as`.proj.common.flutter

import android.content.Context
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import io.flutter.embedding.android.FlutterTextureView
import io.flutter.embedding.android.FlutterView
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
import kotlinx.android.synthetic.main.fragment_flutter.*
import org.devio.`as`.proj.common.R
import org.devio.`as`.proj.common.ui.component.HiBaseFragment
import org.devio.hi.library.util.AppGlobals

abstract class HiFlutterFragment(moduleName: String) : HiBaseFragment() {
    //private lateinit var flutterEngine: FlutterEngine
    private var flutterEngine: FlutterEngine?
    private var flutterView: FlutterView? = null

    //abstract val moduleName: String?
    private val cached = HiFlutterCacheManager.instance!!.hasCached(moduleName)

    //override fun onAttach(context: Context) {
    //    super.onAttach(context)
    //   flutterEngine = FlutterEngine(context)
    //   flutterEngine.dartExecutor.executeDartEntrypoint(DartExecutor.DartEntrypoint.createDefault())
    //}

    init {
        flutterEngine =
            HiFlutterCacheManager.instance!!.getCachedFlutterEngine(AppGlobals.get(), moduleName)
    }

    override fun getLayoutId(): Int {
        return R.layout.fragment_flutter
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        (layoutView as ViewGroup).addView(createFlutterView(activity!!))
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        // 注册flutter/platform_views插件以便能够处理native view
        if (!cached) {
            flutterEngine.let {
                it?.platformViewsController?.attach(
                    activity,
                    it.renderer,
                    it.dartExecutor
                )
            }
        }
    }

    private fun createFlutterView(context: Context): FlutterView {
        // 使用FlutterTextureView来进行渲染，以规避FlutterSurfaceView压后台回来后界面被复用的问题
        val flutterTextureView = FlutterTextureView(activity!!)
        flutterView = FlutterView(context, flutterTextureView)
        return flutterView!!
    }

    /**
     * 设置标题
     */
    fun setTitle(titleStr: String) {
        rl_title.visibility = View.VISIBLE
        title_line.visibility = View.VISIBLE
        title.text = titleStr
        //点击标题,Android 调用Flutter,然后Flutter返回给Android
        title.setOnClickListener {
            HiFlutterBridge.instance!!.fire(
                "onRefreshRecommend",
                "so easy",
                object : MethodChannel.Result {
                    override fun notImplemented() {
                        Toast.makeText(context, "dart那边未实现", Toast.LENGTH_SHORT).show()
                    }

                    override fun error(
                        errorCode: String?,
                        errorMessage: String?,
                        errorDetails: Any?
                    ) {
                        Toast.makeText(context, errorMessage, Toast.LENGTH_SHORT).show()
                    }

                    override fun success(result: Any?) {
                        if (result != null) {
                            Toast.makeText(context, result as String, Toast.LENGTH_SHORT).show()
                        }
                    }
                })
        }
    }

    /**
     * 生命周期告知flutter
     */
    override fun onStart() {
        flutterView!!.attachToFlutterEngine(flutterEngine!!)
        super.onStart()
    }

    override fun onResume() {
        super.onResume()
        //for flutter >= v1.17
        flutterEngine!!.lifecycleChannel.appIsResumed()
    }

    override fun onPause() {
        super.onPause()
        flutterEngine!!.lifecycleChannel.appIsInactive()
    }

    override fun onStop() {
        super.onStop()
        flutterEngine!!.lifecycleChannel.appIsPaused()
    }

    override fun onDetach() {
        super.onDetach()
        flutterEngine!!.lifecycleChannel.appIsDetached()
    }

    override fun onDestroy() {
        super.onDestroy()
        flutterView!!.detachFromFlutterEngine()
    }
}